var FileHelper = {
    createFile : function(fileName, data) {
        if (!fileName || !data) {
            return false;
        }
        chrome.tabs.getSelected(null, function(tab) {
            window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024, function(fs) {
                FileHelper.removeAll(fs);
                fs.root.getFile(fileName, {
                    create : true
                }, function(fileEntry) {
                    fileEntry.createWriter(function(fileWriter) {
                        var builder = new WebKitBlobBuilder();
                        for ( var i = 0; i < data.length; i++) {
                            builder.append(data[i]);
                            builder.append('\n');
                        }

                        var blob = builder.getBlob('application/octet-stream');

                        // Download file
                        fileWriter.onwriteend = function() {
                            chrome.tabs.create({
                                "url" : fileEntry.toURL()
                            }, function(tab) {
                            });
                        };
                        fileWriter.write(blob);
                    }, FileHelper.errorHandler);
                }, FileHelper.errorHandler);
            }, FileHelper.errorHandler);
        });
        return true;
    },
    removeAll : function(fs) {
        var dirReader = fs.root.createReader();
        dirReader.readEntries(function(entries) {
            for ( var i = 0, entry; entry = entries[i]; ++i) {
                if (entry.isDirectory) {
                    entry.removeRecursively(function() {
                    }, FileHelper.errorHandler);
                } else {
                    entry.remove(function() {
                    }, FileHelper.errorHandler);
                }
            }
        }, FileHelper.errorHandler);
    },
    errorHandler : function(e) {
        var msg = '';

        switch (e.code) {
        case FileError.QUOTA_EXCEEDED_ERR:
            msg = 'QUOTA_EXCEEDED_ERR';
            break;
        case FileError.NOT_FOUND_ERR:
            msg = 'NOT_FOUND_ERR';
            break;
        case FileError.SECURITY_ERR:
            msg = 'SECURITY_ERR';
            break;
        case FileError.INVALID_MODIFICATION_ERR:
            msg = 'INVALID_MODIFICATION_ERR';
            break;
        case FileError.INVALID_STATE_ERR:
            msg = 'INVALID_STATE_ERR';
            break;
        default:
            msg = 'Unknown Error';
            break;
        }
        ;

        console.log('Error: ' + msg);
    }
};
